package utils

import (
	"bufio"
	"bytes"
	"fmt"
	"image"
	"image/gif"
	"image/jpeg"
	"image/png"
	"strings"

	"github.com/chai2010/webp"
)

func ToWebp(data []byte, fileName string, Quality float32, Lossless bool, Exact bool) (output []byte, err error) {
	var img image.Image
	var byteStream bytes.Buffer
	w := bufio.NewWriter(&byteStream)

	format := getFormat(fileName)
	img, err = decode(data, format)
	if err != nil {
		return nil, err
	}

	options := &webp.Options{Lossless: Lossless, Quality: Quality, Exact: Exact}
	err = webp.Encode(w, img, options)
	if err != nil {
		return nil, err
	}
	return byteStream.Bytes(), nil
}

func decode(data []byte, format string) (image.Image, error) {
	reader := bytes.NewReader(data)
	switch format {
	case "png":
		return png.Decode(reader)
	case "jpg", "jpeg":
		return jpeg.Decode(reader)
	case "gif":
		return gif.Decode(reader)
	case "webp":
		return webp.Decode(reader)
	default:
		return nil, fmt.Errorf("unsupport format")
	}
}

func getFormat(fileName string) string {
	idx := strings.LastIndex(fileName, ".")
	if idx < 0 {
		return ""
	}
	return fileName[idx+1:]
}

func GetOutputFileName(fileName string) string {
	idx := strings.LastIndex(fileName, ".")
	if idx < 0 {
		return ""
	}
	return fileName[:idx+1] + "webp"
}
